<template>
  <view class="container">
    <u-form :model="form" ref="uForm" label-width="180">
      <view class="input-wrapper" @click="showCalendar = true">
        <u-form-item label="请假日期" right-icon="arrow-right" required>
          <text :class="form.beginDate?'normal-text':'light-text' ">{{ askLeaveStr }}</text>
        </u-form-item>
      </view>
      <u-form-item label="请假天数">
        <text :class="passAskLeaveDays === false?'error-text':'normal-text' ">{{ form.askLeaveDaysStr }}</text>
      </u-form-item>
      <u-form-item v-show="askLeaveConfig.enableAlDaysAudit" label="请假限制天数">
        <u-input v-model="askLeaveConfig.alDaysLimit" disabled/>
      </u-form-item>
      <u-form-item v-show="reqLeaveReason" label="请假原因" prop="leaveReason" :required="reqLeaveReason">
        <u-input v-model="form.leaveReason" type="textarea" :maxlength="leaveReasonLimit" :border="true"
                 placeholder="请填写请假原因"/>
      </u-form-item>

      <u-button type="primary" shape="square" :ripple="true" size="default" @click="preSubmit" class="custom-btn"
      >提交
      </u-button>
    </u-form>

    <!-- 日历 -->
    <u-calendar v-model="showCalendar" :mode="calendarMode" :max-date="maxDate" @change="onCalendarChange"
                :safe-area-inset-bottom="true" :min-date="minDate"></u-calendar>

    <!-- 确认对话框 -->
    <u-modal
        v-model="showModal"
        content="确认提交本次请假?"
        @confirm="submit"
        @cancel="onCancel"
        show-cancel-button
    ></u-modal>

    <!-- Toast -->
    <u-toast ref="uToast"/>

  </view>
</template>

<script>
import {addDay, addYear, formatYmd, getDiffDays} from "@/utils/index.js";
import askLeaveApi from "@/api/modules/askLeave";
import {handleGoTo} from '@/utils/askLeaveRouter.js'

export default {
  name: "LeaveRequest",
  data() {
    return {
      // 请假配置
      askLeaveConfig: {
        enableAlAudit: false
      },
      // 请假天数是否通过验证
      passAskLeaveDays: true,
      form: {
        // 起始日期
        beginDate: null,
        // 结束日期
        endDate: null,
        // 请假理由
        leaveReason: null,
        // 请假天数
        askLeaveDays: 0,
        // 请假天数描述
        askLeaveDaysStr: '共请假0天',
      },
      // 是否显示确认对话框
      showModal: false,
      // 请假理由是否必填
      reqLeaveReason: false,
      // 请假理由字数限制
      leaveReasonLimit: 50,
      // 最小可选日期
      minDate: '1950-01-01',
      // 是否显示日历
      showCalendar: false,
      // 日历最大可选日期
      maxDate: '2022-12-01',
      // 日历模式
      calendarMode: 'range',
      rules: {
        leaveReason: [
          {
            required: false,
            message: "请输入请假理由",
            trigger: "change",
          },
        ]
      },
      // 请假日期
      askLeaveStr: '选择请假日期'
    }
  },
  methods: {
    // 提交
    async submit() {
      try {
        const res = await askLeaveApi.doAskLeave(this.form)
        if (res.code === 200) {
          this.$refs.uToast.show({
            title: '请假成功',
            type: 'success',
          })
          // 请假成功后跳转到当前请假状态页
          setTimeout(() => handleGoTo(), 2000)
        }
      } catch (e) {

      }
    },
    // 校验请假天数
    validateLeaveDays() {
      if (!this.askLeaveConfig) {
        return true;
      }
      if (!this.askLeaveConfig.enableAlDaysAudit) {
        return true;
      }
      return this.form.askLeaveDays <= this.askLeaveConfig.alDaysLimit;
    },
    // 预提交
    async preSubmit() {
      if (!this.form.beginDate || !this.form.endDate) {
        this.$refs.uToast.show({
          title: '请选择请假时间',
          type: 'error',
        })
        return
      }
      if (!this.passAskLeaveDays) {
        this.$refs.uToast.show({
          title: '当前请假天数超过请假天数限制',
          type: 'error',
        })
        return
      }
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.showModal = true;
        }
      });
    },
    // 取消提交
    onCancel() {
      this.showModal = false
    },
    // 日历确定事件处理
    onCalendarChange(value) {
      this.form.beginDate = value.startDate
      this.form.endDate = value.endDate
      this.askLeaveStr = `${value.startDate} 至 ${value.endDate}`
      let start = new Date(value.startDate)
      let end = new Date(value.endDate)
      // 因为结束日期是休假的最后1天,所以这里需要把结束日期再加1天,从而得出总请假天数
      end = addDay(end, 1)
      const diffDays = getDiffDays(start, end)
      this.form.askLeaveDays = diffDays
      if (!this.validateLeaveDays()) {
        this.passAskLeaveDays = false
        this.$refs.uToast.show({
          title: '当前请假天数超过请假天数限制',
          type: 'error',
        })
        this.form.askLeaveDaysStr = `请假天数超出限制`
        return
      } else {
        this.passAskLeaveDays = true
      }
      this.form.askLeaveDaysStr = `共请假${diffDays}天`
    },
    // 初始化日历可选最大日期
    initMaxDate() {
      // 默认可选最大日期是10年后的今天
      let curDate = new Date()
      curDate = addYear(curDate, 10)
      this.maxDate = formatYmd(curDate)
    },
    // 初始化日历可选最小日期
    initMinDate() {
      // 请假可选日期必须大于今天
      // 若当前时间>21点,可选日期则必须大于明天
      let curDate = new Date()
      const curHours = curDate.getHours();
      if (curHours >= 21) {
        curDate = addDay(curDate, 2)
      } else {
        curDate = addDay(curDate, 1)
      }
      this.minDate = formatYmd(curDate)
    },
    // 查询当前请假配置
    async getAskLeaveConfig() {
      const res = await askLeaveApi.getAskLeaveConfig()
      this.askLeaveConfig = res.data.data
      if (this.askLeaveConfig.enableAlAudit === true) {
        this.reqLeaveReason = true
        this.rules.leaveReason[0].required = true
      }
    }
  },
  onReady() {
    this.getAskLeaveConfig()
    this.initMinDate()
    this.initMaxDate()
    this.$refs.uForm.setRules(this.rules);
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  padding-left: 16px;
  padding-right: 16px;
  box-sizing: border-box;

  .custom-btn {
    margin: 15px auto;
    left: 50%;
    transform: translateX(-50%);
  }

  .light-text {
    color: rgb(192, 196, 204);
  }

  .normal-text {
    color: #303133;
  }

  .error-text {
    color: #FA3B3A;
  }

}
</style>
